package nl.altenpts.net.broker;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.util.Iterator;
import java.util.LinkedList;

/**
 * An OutgoingMessage. The payload of the message is a list of ByteBuffers.
 * @author fabian
 *
 */

public class OutgoingMessage {
	
	/**
	 * Constructs a new OutgoingMessage with an empty payload.
	 * @param host The target host
	 * @param port The target port
	 */
	public OutgoingMessage(InetSocketAddress address) {
		this.address = address;
	}
	
	
	/**
	 * Prepends the specified ByteBuffer to the message payload
	 * 
	 * @param content to be prepended to message payload
	 */
	public void appendContent(ByteBuffer content) {
		payload.addLast(content);
		length += content.remaining();
	}
	

	/**
	 * Appends the specified ByteBuffer to the message payload
	 * 
	 * @param content to be appended to message payload
	 */
	public void prependContent(ByteBuffer content) {
		payload.addFirst(content);
		length += content.remaining();
	}
	
	/**
	 * //TODO
	 */
	public InetSocketAddress getAddress() {
		return address;
	}
	
	/**
	 * Returns the length of the full message
	 * 
	 * @return length of message
	 */
	public int getLength() {
		return length;
	}
	
	/**
	 * The list of ByteBuffer that comprise the message payload
	 * 
	 * @return message payload.
	 */
	public LinkedList<ByteBuffer> getPayload() {
		return payload;
	}
	
	/**
	 * Copies the payload buffers to a single ByteBuffer
	 * 
	 * @param buffer
	 */
	public void toBuffer(ByteBuffer buffer) {
		Iterator<ByteBuffer> iterator = payload.iterator();
		while(iterator.hasNext()) {
			ByteBuffer buf = iterator.next();
			buf.mark();
			buffer.put(buf);
			buf.reset();
		}
	}
	
	private int length = 0;
	private LinkedList<ByteBuffer> payload = new LinkedList<ByteBuffer>();
	private InetSocketAddress address;
	
}
 